package com.sjd.provider;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.sjd.common.core.domain.AjaxResult;
import com.sjd.common.utils.DateUtils;
import com.sjd.web.config.OssConfig;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * oss服务提供类
 */
@Component
@AllArgsConstructor
public class FileOssServerProvider {
    private final OssConfig ossConfig;

    /**
     * 根据provider标识选择oss服务商
     * @param provider provider
     * @return AjaxResult
     */
    public AjaxResult ossAuthByProvider(String provider) {
        if (OssConfig.Provider.ALI.equals(provider)) {
            OssConfig.AliOss aliOss = ossConfig.getAliOss();
            String accessId = aliOss.getAccessId();
            String accessKey = aliOss.getAccessKey();
            String endpoint = aliOss.getEndpoint();
            String bucket = aliOss.getBucket();
            String host = "https://" + bucket + "." + endpoint;
            String dir = "sjd/" + DateUtils.getDate() + "/";
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessId, accessKey);
            try {
                long expireTime = aliOss.getExpireTime();
                long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
                Date expiration = new Date(expireEndTime);
                // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
                PolicyConditions conditions = new PolicyConditions();
                conditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
                conditions.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

                String postPolicy = ossClient.generatePostPolicy(expiration, conditions);
                byte[] binaryData = postPolicy.getBytes(StandardCharsets.UTF_8);
                String encodedPolicy = BinaryUtil.toBase64String(binaryData);
                String postSignature = ossClient.calculatePostSignature(postPolicy);

                Map<String,String> ossResult = new HashMap<>(8);
                ossResult.put("OSSAccessKeyId", accessId);
                ossResult.put("policy", encodedPolicy);
                ossResult.put("Signature", postSignature);
                ossResult.put("dir", dir);
                ossResult.put("host", host);
                ossResult.put("expire", String.valueOf(expireEndTime / 1000));
                return AjaxResult.success(ossResult);
            } catch (Exception e) {
                return AjaxResult.error(e.getMessage());
            } finally {
                ossClient.shutdown();
            }
        } else if (OssConfig.Provider.TX.equals(provider)) {
            return AjaxResult.error("腾讯云oss服务待对接，请等待");
        } else {
            return AjaxResult.error("不支持的提供方【" + provider + "】，请等待拓展");
        }
    }
}
